//
//  YLYCalculatorView.m
//  hohoho
//
//  Created by 楊盧银Mac on 14-4-26.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#import "YLYCalculatorView.h"

@implementation YLYCalculatorView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
-(void)awakeFromNib{
    [self initCalulatorView];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)initCalulatorView
{
    
    //设置背景图片
//    NSBundle *bundle=[NSBundle mainBundle];
//    NSData *data=[[NSData alloc]initWithContentsOfFile:
//                  [bundle pathForResource:@"1" ofType:@"jpg"]];//找到NSBundle的某一资源
//    UIImage *img=[UIImage imageWithData:data];//创建了可用的图像对象
//    [self.view setBackgroundColor:[UIColor colorWithPatternImage:img]];//UIColor colorWithPatternImage:方法是把图片转化为color类型  将背景换做提供的图片
    
    //    //添加提示性文字
    //    UIAlertView *alex=[[UIAlertView alloc]initWithTitle:@"使用说明" message:@"只支持两数的计算以及在此基础上的计算，不支持连算。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    //    [alex show];
    //    [alex release];
    
    //创建标签

    int keyX = self.frame.size.width/5;
    int keyY = self.frame.size.height/4;
    self.showNumberLabel=[[UILabel alloc]initWithFrame:CGRectMake(90, 40, 200, 50)];
//    [self addSubview:self.label];
//    self.label.backgroundColor=[UIColor clearColor];//清空背景颜色
//    self.label.textColor=[UIColor blueColor];//字体颜色
//    self.label.textAlignment=NSTextAlignmentRight;//字体居右
//    self.label.font=[UIFont systemFontOfSize:32.4];
    
    //添加1-9数字
    NSArray *array=[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];
    int n = 0;
    int k = 0;
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++)
        {
            self.button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            self.button.frame=CGRectMake(keyX*(j+1), keyY*i, keyX-1, keyY-1);
            [self.button setTitle:[array objectAtIndex:n++] forState:UIControlStateNormal];
            [self addSubview:self.button];
            self.button.tag = [[array objectAtIndex:k++] intValue];
            self.button.layer.borderWidth = 2;
            [self.button addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    //单独添加0
    UIButton *button0=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button0 setFrame:CGRectMake(keyX*2, keyY*3, keyX-1, keyY)];
    [button0 setTitle:@"0" forState:UIControlStateNormal];
    [button0 addTarget:self action:@selector(one:) forControlEvents:UIControlEventTouchUpInside];
    button0.layer.borderWidth =2;
    [self addSubview:button0];
    
    
    //添加运算符
    
    NSArray *array1=[NSArray arrayWithObjects:@"+",@"-",@"*",@"/",nil];
    for (int i=0; i<4; i++)
    {
        UIButton *button1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button1 setFrame:CGRectMake(0, keyY*i, keyX-1, keyY-1)];
        [button1 setTitle:[array1 objectAtIndex:i] forState:UIControlStateNormal];
        [self addSubview:button1];
        button1.tag = i;
        [button1 addTarget:self action:@selector(two:) forControlEvents:UIControlEventTouchUpInside];
        button1.layer.borderWidth = 2;
        button1.layer.cornerRadius = button0.frame.size.height/2;
    }
    
    //添加=
    
    UIButton *button2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    [button2 setFrame:CGRectMake(keyX*4, keyY*2, keyX, keyY*2)];
    
    [button2 setTitle:@"=" forState:UIControlStateNormal];
    
    [button2 addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button2];
    button2.layer.borderWidth = 2;
    
    //添加清除键
    
    UIButton *button3=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button3 setFrame:CGRectMake(keyX, keyY*3, keyX-1, keyY)];
    [button3 setTitle:@"AC" forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    button3.layer.borderWidth = 2;
    button3.tag = 1;
    [self addSubview:button3];
    
    //添加.
    
    UIButton *button4=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button4 setFrame:CGRectMake(keyX*3, keyY*3, keyX-1, keyY)];
    [button4 setTitle:@"." forState:UIControlStateNormal];
    [button4 addTarget:self action:@selector(dotPress:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button4];
    button4.layer.borderWidth = 2;
    
    //后退
    
    UIButton *button5=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button5 setFrame:CGRectMake(keyX*4, keyY, keyX, keyY-1)];
    [button5 setTitle:@"<<－" forState:UIControlStateNormal];
    [button5 addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    button5.tag = 0;
    button5.layer.borderWidth = 2;
    [self addSubview:button5];
    //隐藏
    
    UIButton *button6=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button6 setFrame:CGRectMake(keyX*4, 0, keyX, keyY-1)];
    [button6 setTitle:@"完成" forState:UIControlStateNormal];
    [button6 addTarget:self action:@selector(hildeView:) forControlEvents:UIControlEventTouchUpInside];
    button6.layer.borderWidth = 2;
    [self addSubview:button6];

    // Do any additional setup after loading the view, typically from a nib.
}
- (void) inition{
	numberCount = 0;
	isDotDown = NO;
	isCal = NO;
	isOverFlow=NO;
	isPreOper = NO;
	afterDotNumber = 0;
	num1 = 0;
	num2 = 0;
	currentOperatorType = operatorNoType;
	self.showNumberLabel.text = @"0";
	currentNumber = 0;
}
- (NSString *)changeFloat:(double)Right
{
	NSString *stringFloat;
	stringFloat = [NSString stringWithFormat:@"%.10f",Right];
	const char *floatChars = [stringFloat UTF8String];
    NSUInteger length = [stringFloat length];
	int i;
    for( i = length-1; i>=0; i--)
    {
        if(floatChars[i] == '0')
			;
		else
		{
            if(floatChars[i] == '.')
                i--;
            break;
        }
    }
    NSString *returnString;
    if(i == -1)
        returnString = @"0";
	else
        returnString = [stringFloat substringToIndex:i+1];
    return returnString;
}
-(void)dotPress:(id)sender{
    if(isCal)
		flag = YES;
	if(!isDotDown && !isCal && !isPreOper)
	{
		self.showNumberLabel.text = [NSString stringWithFormat:@"%@%@",self.showNumberLabel.text,@"."];
		isDotDown = YES;
	}
	else if(!isDotDown&&(isCal || isPreOper))
	{
		num2 = 0;
		self.showNumberLabel.text = @"0.";
		isDotDown = YES;
	}
}
-(void)one:(id)sender
{
    
    NSInteger number = [sender tag];
	if(numberCount == 0||numberCount == 1)
	{
		if([self.showNumberLabel.text length]>=9 && !isExp)
		{
			return;
		}
		isExp = NO;
		isPreOper = NO;
		numberCount = 1;
		if(isCal)
		{
			[self inition];
			if(flag)
			{
				self.showNumberLabel.text = @"0.";
				isDotDown = YES;
				flag = NO;
			}
		}
		
		if(!isDotDown)
		{
			num1 = num1 * 10 +  number;
			self.showNumberLabel.text = [self changeFloat: num1];
		}
		else{
			
			afterDotNumber ++;
			if(number == 0)
				self.showNumberLabel.text = [NSString stringWithFormat:@"%@%@",self.showNumberLabel.text,@"0"];
			else
			{
                NSArray *array = [self.showNumberLabel.text componentsSeparatedByString:@"."];
                if ([array[1] length] > 1) {
                    return;
                }
				num1 = num1 + pow(0.1,afterDotNumber) * number;
                if ([self.showNumberLabel.text isEqualToString:@"(null)."]) {
                    self.showNumberLabel.text = @"0.";
                }
                
				self.showNumberLabel.text=[NSString stringWithFormat:@"%@%ld",self.showNumberLabel.text,(long)number];
				
			}
		}
		currentNumber = num1;
	}
	else if(numberCount == 2)
	{
		if([self.showNumberLabel.text length] >= 9)
		{
			if(!isPreOper)
                return;
		}
		
		isPreOper = NO;
		if(!isDotDown)
		{
			
			num2 = num2 * 10 + number;
			self.showNumberLabel.text = [self changeFloat: num2];
		}
		else
		{
			afterDotNumber++;
			
			if(number == 0)
				self.showNumberLabel.text = [NSString stringWithFormat:@"%@%@",self.showNumberLabel.text,@"0"];
			else
			{
				NSArray *array = [self.showNumberLabel.text componentsSeparatedByString:@"."];
                if ([array[1] length] > 1) {
                    return;
                }
				num2 = num2 + pow(0.1,afterDotNumber) * number;
                
				self.showNumberLabel.text=[NSString stringWithFormat:@"%@%ld",self.showNumberLabel.text,(long)number];
			}
		}
		currentNumber = num2;
	}
	currentafterNumber=afterDotNumber;
    [self.delegate showCalculator:self.showNumberLabel.text];
}

-(void)two:(id)sender
{
    if(numberCount == 2&& !isPreOper)
	{
		isPreOper = YES;
		[self equResult];
	}
	currentOperatorType = [sender tag];
	numberCount = 2 ;
	isPreOper = YES;
	isDotDown = NO;
	isOverFlow=NO;
	isCal = NO;
	num2 = 0;
	afterDotNumber = 0;
    [self.delegate showCalculator:self.showNumberLabel.text];
}

- (void) equResult
{
	switch(currentOperatorType)
	{
		case operatorTypePlus:
			num1 = num1 + num2;
			break;
		case operatorTypeMinus:
			num1 = num1 - num2;
			break;
		case operatorTypeMul:
			num1 = num1 * num2;
			break;
		case operatorTypeDiv:
			if(num2 == 0)
			{
				self.showNumberLabel.text = @"Error";
				[self showMessage:@"the divided number can't be Zero"];
				return;
			}
			num1 = num1 / num2;
			break;
	}
	currentNumber = num1;
    num1 = [[NSString stringWithFormat:@"%.2f",num1] doubleValue];
	isOverFlow=NO;
	if([[self changeFloat:num1] length] >= 15)
	{
		self.showNumberLabel.text = [NSString stringWithFormat:@"%e",num1];
		isExp = YES;
	}
	else if([[self changeFloat: num1] isEqualToString:@"-0"])
		self.showNumberLabel.text = @"0";
	else
		self.showNumberLabel.text = [self changeFloat: num1];
}
-(void)showMessage:(NSString *) msg//利用提示框显示提示信息
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
													message:msg
												   delegate:self
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
	[alert show];
	//[alert release];
}
-(void)go:(id)sender
{
    
    if(numberCount == 1 && isPreOper)
	{
		NSString *temp = self.showNumberLabel.text;
		[self inition];
		self.showNumberLabel.text = temp;
	}
	else if(numberCount >= 1&&!isPreOper)
	{
		[self equResult];
		if([[self changeFloat: num1] length] >=9)
			isExp=YES;
		isCal = YES;
		isPreOper = NO;
		numberCount = 1;
		isDotDown = NO;
		afterDotNumber = 0;
	}
	else if(numberCount == 2 && isPreOper)
	{
		
		num2 = isDotDown ? 0 : num1;
		[self equResult];
		isCal = YES;
		isPreOper = NO;
		numberCount = 1;
		isDotDown = NO;
		afterDotNumber = 0;
	}
    [self.delegate showCalculator:self.showNumberLabel.text];
    
    
}

//当按下清除建时，所有数据清零

//返回键
-(void)back:(id)sender
{
    if([sender tag] == 0)
	{
		//后退操作
		if(numberCount == 1)
		{
			if(isCal)
			{
				[self inition];
				return;
			}
			if(isDotDown&&afterDotNumber > 0)
			{
				NSString *desiredNumber = [self.showNumberLabel.text substringWithRange:NSMakeRange(0,[self.showNumberLabel.text length]-1)];
				afterDotNumber--;
				self.showNumberLabel.text = desiredNumber;
				num1 = [desiredNumber floatValue];
				NSLog(@"num1: %f",num1);
			}
			else {
				num1 = (int)(num1 / 10);
				isDotDown = NO;
				self.showNumberLabel.text = [self changeFloat: num1];
			}
		}
		else if(numberCount == 2)
		{
			if(isDotDown&&afterDotNumber > 0)
			{
				NSString *desiredNumber = [self.showNumberLabel.text substringWithRange:NSMakeRange(0,[self.showNumberLabel.text length]-1)];
				afterDotNumber--;
				self.showNumberLabel.text = desiredNumber;
				num2 = [desiredNumber floatValue];
				NSLog(@"num2: %f",num2);
			}
			else {
				num2 = (int)(num2/10);
				isDotDown = NO;
				self.showNumberLabel.text = [self changeFloat: num2];
			}
		}
	}
	else//完全清零(初始化)
	{
		[self inition];
	}
    [self.delegate showCalculator:self.showNumberLabel.text];
    
}
-(void)hildeView:(id)sender{
    [self.delegate quitCalculator];
}

@end
